package com.zll.onlineExam.activities;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.fastjson.JSONObject;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.zll.onlineExam.R;
import com.zll.onlineExam.adapter.RankingItemViewAdapter;
import com.zll.onlineExam.ajax.Ajax;
import com.zll.onlineExam.ajax.HTTPConfig;
import com.zll.onlineExam.ajax.ReqCallback;
import com.zll.onlineExam.entity.out.UserDtoOut;
import com.zll.onlineExam.utils.XToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RankingActivity extends AppCompatActivity implements View.OnClickListener {

    private RefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private ImageView mBack;
    private RankingItemViewAdapter mAdapter;
    private Map<String,Object> parmas;
    private int curPage = 1;
    private int curRows = 5;

    private static Handler mHandler;
    private static DataHolder mRefresh;
    private static DataHolder mLoadMore;

    private final int LOAD_SUCCESS = 3;
    private final int LOAD_FAIL = 2;
    private final int FETCH_SUCCESS = 1;
    private final int FETCH_FAIL = 0;
    private final int FETCH_ERROR = -1;

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back){
            finish();
        }
    }


    private class DataHolder{
        private List<UserDtoOut> data;
        private RefreshLayout refreshLayout;

        public List<UserDtoOut> getData() {
            return data;
        }

        public DataHolder setData(List<UserDtoOut> data) {
            this.data = data;
            return this;
        }

        public RefreshLayout getRefreshLayout() {
            return refreshLayout;
        }

        public DataHolder setRefreshLayout(RefreshLayout refreshLayout) {
            this.refreshLayout = refreshLayout;
            return this;
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ranking);initView();
        initListener();
        initHandler();

        mRefresh = new DataHolder();
        mLoadMore = new DataHolder();

    }
    private void initView() {
        mRefreshLayout = findViewById(R.id.refreshLayout);
        mRecyclerView = findViewById(R.id.recyclerView);
        mBack = findViewById(R.id.iv_back);
        parmas = new HashMap<>();
        parmas.put("page","");
        parmas.put("row","");
    }

    private void initListener() {
        mBack.setOnClickListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(this));
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mRefresh.setRefreshLayout(refreshlayout);
                refreshData(curPage,curRows);
            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                mLoadMore.setRefreshLayout(refreshlayout);
                curRows+=5;
                loadData(curPage,curRows);
            }
        });

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new RankingItemViewAdapter(new ArrayList<>(),this);
        mRecyclerView.setAdapter(mAdapter);

        // 自动首次刷新
        mRefreshLayout.autoRefresh();
    }


    private void initHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case FETCH_SUCCESS:
                        mAdapter.setData(mRefresh.getData());
                        mRefresh.getRefreshLayout().finishRefresh(true);
                        break;
                    case LOAD_SUCCESS:
                        if(mAdapter.getDataList().size() == mLoadMore.getData().size()){
                            XToastUtils.info("没有更多数据了");
                        }
                        mLoadMore.getRefreshLayout().finishLoadMore(true);
                        mAdapter.setData(mLoadMore.getData());
                        break;
                    case FETCH_FAIL:
                        mRefresh.getRefreshLayout().finishRefresh(false);
                        break;
                    case LOAD_FAIL:
                        mLoadMore.getRefreshLayout().finishLoadMore(false);
                        break;
                    case FETCH_ERROR:
                        XToastUtils.error("网络异常");
                        break;
                    default:
                        break;

                }

            }
        };
    }


    public void refreshData(int page,int row){
        parmas.put("page", String.valueOf(page));
        parmas.put("row", String.valueOf(row));
        Ajax.post(HTTPConfig.LIST_USER_RANKING, parmas, new ReqCallback() {
            @Override
            public void onSuccess(JSONObject resp) {
                List<UserDtoOut> dtoOutList = resp.getJSONArray("data").toJavaList(UserDtoOut.class);
                mRefresh.setData(dtoOutList);
                mHandler.sendEmptyMessage(FETCH_SUCCESS);
            }

            @Override
            public void onFail(String msg) {
                mHandler.sendEmptyMessage(FETCH_FAIL);
            }

            @Override
            public void onError(String msg) {
                mHandler.sendEmptyMessage(FETCH_ERROR);
            }
        });
    }

    public void loadData(int page,int row){
        parmas.put("page", String.valueOf(page));
        parmas.put("row", String.valueOf(row));
        Ajax.post(HTTPConfig.LIST_USER_RANKING, parmas, new ReqCallback() {
            @Override
            public void onSuccess(JSONObject resp) {
                List<UserDtoOut> dtoOutList = resp.getJSONArray("data").toJavaList(UserDtoOut.class);
                mLoadMore.setData(dtoOutList);
                mHandler.sendEmptyMessage(LOAD_SUCCESS);
            }

            @Override
            public void onFail(String msg) {
                mHandler.sendEmptyMessage(LOAD_FAIL);
            }

            @Override
            public void onError(String msg) {
                mHandler.sendEmptyMessage(FETCH_ERROR);
            }
        });
    }

}